//
//  ZDBHomeViewController.m
//  ZDB
//
//  Created by on 2020/3/14.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBHomeViewController.h"
#import "ZDBHomeTableHeadView.h"
#import "ZDBHomeTableViewCell.h"
#import "ZDBExtensionViewController.h"
#import "ZDBBanner.h"
#import "ZDBShareCircleViewController.h"
#import "ZDBBindWXViewController.h"
#import "ZDBNewsInfoViewController.h"
#import "ZDBHomeTastModel.h"
#import "ZDBAlwaysTaskTableViewCell.h"
#import "ZDBAlwaysTaskVC.h"
#import "ZDBRechargeViewController.h"
#import "ZDBNewsListViewController.h"
#import "ZDBRedEnvelopesCustomAlertView.h"

#define headViewHeight 220
@interface ZDBHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray;//数据
@property (nonatomic, strong) NSMutableArray * newsArray;//新闻公告
@property (nonatomic, strong) NSMutableArray * banneArray;//数组图片
@property (nonatomic,strong) ZDBHomeTableHeadView * tableviewHeadView;
@end

@implementation ZDBHomeViewController
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
 // 判断要显示的控制器是否是自己
   BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
   [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =  RGBA(249, 249, 249, 1);
    [self.view addSubview:self.tableviewHeadView];
    [self.view addSubview:self.tableView];
    WeakSelf
    // 上拉加载
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       
        [weakSelf getTaskData];
        if (weakSelf.banneArray.count==0)
        {
            [self notice_getList];
        }
    }];
    [header beginRefreshing];
    self.tableView.mj_header = header;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoginSusess) name:LoginSusessNotificationse object:nil];
    [self getCheckRed];
}
- (void)LoginSusess
{
     [self getTaskData];
     [self getCheckRed];
}
//检查是否有红包
- (void)getCheckRed
{
    
    WeakSelf
      NSString  * banber = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"checkRed"];
      [[SmileHttpTool sharedInstance] POST:banber parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
          NSDictionary * dic = responseObject;
          if (!kDictIsEmpty(dic)) {
              if ([dic[@"statusCode"] integerValue] ==0) {//可领取红包
                  ZDBRedEnvelopesCustomAlertView * redEnvelView = [[ZDBRedEnvelopesCustomAlertView  alloc] initWithimage:@""];
                  [redEnvelView showLXAlertView];
              }
          }
    } failure:^(id responseObject, NSError *error) {
         
        
      }];
}
//获取公共和banner
- (void)notice_getList
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * banber = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"notice_getList"];
    [[SmileHttpTool sharedInstance] POST:banber parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {

        NSDictionary * dic = responseObject[@"data"];
        if (!kDictIsEmpty(dic)) {
            NSArray * bannerInfos = dic[@"bannerInfos"];
            weakSelf.banneArray = [ZDBBanner mj_objectArrayWithKeyValuesArray:bannerInfos];
            NSMutableArray * imgs = [NSMutableArray new];
            for (ZDBBanner * banner in weakSelf.banneArray)
            {
                [imgs addObject:kFormat(@"%@", banner.imageUrl)];
            }
            weakSelf.tableviewHeadView.scrollView.data = imgs;
            
            NSArray * noticeInfos = dic[@"noticeInfos"];
            weakSelf.newsArray = [ZDBNotice mj_objectArrayWithKeyValuesArray:noticeInfos];
            NSMutableArray * titles = [NSMutableArray new];
            for (ZDBNotice * notice in weakSelf.newsArray)
            {
                [titles addObject:notice.title];
            }
            weakSelf.tableviewHeadView.advertScrollViewCenter.titles = titles;
        }
        [self stopLoadingAnimation];
  } failure:^(id responseObject, NSError *error) {
         [self stopLoadingAnimation];
      
    }];

}
- (ZDBHomeTableHeadView*)tableviewHeadView{
    WeakSelf
    if (!_tableviewHeadView) {
        _tableviewHeadView =[[ ZDBHomeTableHeadView alloc]initWithFrame:CGRectMake(0, IPhoneTopHeight, UIScreenWidth, headViewHeight)];
        //        公告详情
        _tableviewHeadView.Advertblock = ^(NSInteger index) {
            ZDBNotice * notice = weakSelf.newsArray[index];
            ZDBNewsInfoViewController * newsVC = [[ZDBNewsInfoViewController alloc] init];
            newsVC.title = @"公告详情";
            newsVC.model = notice;
            [weakSelf.navigationController pushViewController:newsVC animated:YES];
        };
        //        bancels--URL
        _tableviewHeadView.BancelsUrlblock = ^(NSInteger index) {
          ZDBBanner * banner = weakSelf.banneArray[index];
            if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:banner.url]])
            {
                
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:banner.url] options:@{} completionHandler:nil];
                } else {
                    // Fallback on earlier versions
                }
            }else
            {
                if (@available(iOS 10.0, *)) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:banner.url] options:@{} completionHandler:nil];
                } else {
                    // Fallback on earlier versions
                }
            }
            
            
        };
        [_tableviewHeadView.moreBtn add_BtnClickHandler:^(NSInteger tag) {//更多
            
            ZDBNewsListViewController * newsListVC = [[ZDBNewsListViewController alloc] init];
            newsListVC.title = @"公告列表";
            newsListVC.dataSource = weakSelf.newsArray;
            [weakSelf.navigationController pushViewController:newsListVC animated:YES];
            
        }];
    }
    return _tableviewHeadView;
}
#pragma 获取任务列表
- (void)getTaskData
{
    WeakSelf
    NSString  * getTaskInfo = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getTaskInfo"];
    [[SmileHttpTool sharedInstance] POST:getTaskInfo parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        
        NSDictionary * dic = responseObject[@"data"];
        if (!kDictIsEmpty(dic)) {
            [weakSelf.dataArray removeAllObjects];
            
            NSArray *  taskInfoList = dic[@"taskInfoList"];//一级数据
            NSArray *  taskRecharges = dic[@"taskRecharges"];//3级数据
            NSArray *  taskRegisters = dic[@"taskRegisters"];//2级数据
            NSArray *oneTaskArray = [TaskInfoListModel mj_objectArrayWithKeyValuesArray:taskInfoList];
            NSArray *twoTaskArray = [TaskRegistersModel mj_objectArrayWithKeyValuesArray:taskRegisters];
            NSArray *threeTaskArray = [TaskRechargesModel mj_objectArrayWithKeyValuesArray:taskRecharges];
          
            ZDBHomeTastModel * model = [[ZDBHomeTastModel alloc] init];
            model.content = @"邀请好友 组队赚钱";
            model.title = @"永久任务";
            model.dataArray  = @[@""];
            model.type = 1;
            [weakSelf.dataArray addObject:model];
            
            if (oneTaskArray.count>0) {
                ZDBHomeTastModel * oneModel = [[ZDBHomeTastModel alloc] init];
                oneModel.title = @"掌兑推荐";
                oneModel.content = @"图文转发，简单快速";
                oneModel.dataArray  = oneTaskArray;
                oneModel.type = 2;
                [weakSelf.dataArray addObject:oneModel];
            }
            if (twoTaskArray.count>0) {
                ZDBHomeTastModel * twoModel = [[ZDBHomeTastModel alloc] init];
                twoModel.title = @"掌兑精选";
                twoModel.content = @"邀请注册，佣金丰厚";
                twoModel.dataArray  = twoTaskArray;
                twoModel.type = 3;
                [weakSelf.dataArray addObject:twoModel];
            }
            if (threeTaskArray.count>0) {
                ZDBHomeTastModel * treeModel = [[ZDBHomeTastModel alloc] init];
                treeModel.title = @"掌兑精选";
                treeModel.content = @"试玩应用，充值高返";
                treeModel.dataArray  = threeTaskArray;
                treeModel.type = 4;
                [weakSelf.dataArray addObject:treeModel];
            }
            [weakSelf.tableView reloadData];
            
        }
        [weakSelf.tableView.mj_header endRefreshing];
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        
    }];
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, IPhoneTopHeight, UIScreenWidth, UIScreenHeight - IPhoneTopHeight - TABBAR_HEIGHT)style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor =  RGBA(249, 249, 249, 1);
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerNib:[UINib nibWithNibName:@"ZDBHomeTableViewCell" bundle:nil]  forCellReuseIdentifier:@"ZDBHomeTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"ZDBAlwaysTaskTableViewCell" bundle:nil]  forCellReuseIdentifier:@"ZDBAlwaysTaskTableViewCell"];
        
        _tableView.tableHeaderView =self.tableviewHeadView;
    }
    return _tableView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    ZDBHomeTastModel * model = _dataArray[section];
    return model.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ZDBHomeTastModel * model = _dataArray[section];
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)];
    view.backgroundColor = self.view.backgroundColor;
    UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(28,8, 0, 20)];
    titleLab.font = AutoBoldFont(18);
    titleLab.text = model.title;
    titleLab.textColor = MAINCOLOR;
    [titleLab sizeToFit];
    titleLab.width = titleLab.width+2;
    titleLab.height = 21;
    [view addSubview:titleLab];
    UILabel * mosLab = [[UILabel alloc] initWithFrame:CGRectMake(titleLab.right+6, 0, 190, 10)];
    mosLab.bottom = titleLab.bottom-2;
    mosLab.textColor = MAINTITLECOLOR1;
    mosLab.font = AutoFont(10);
    mosLab.text = model.content;
    [view addSubview:mosLab];
    
    UIImageView * lineView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, 4, 20)];
    lineView.centerY = titleLab.centerY;
    lineView.image = [UIImage imageNamed:@"jianbian"];
    [view addSubview:lineView];
    return view;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        
        ZDBAlwaysTaskTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"ZDBAlwaysTaskTableViewCell" forIndexPath:indexPath];
               return cell;
    }else
    {
         ZDBHomeTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"ZDBHomeTableViewCell" forIndexPath:indexPath];
         ZDBHomeTastModel * model = _dataArray[indexPath.section];
        if (model.type==2)//任务1
        {
            cell.oneTaskModel = model.dataArray[indexPath.row];
        }else if (model.type==3)//任务2
        {
            cell.twoTaskModel = model.dataArray[indexPath.row];
            
        }else if (model.type==4)//任务3
        {
            cell.threeTaskModel = model.dataArray[indexPath.row];
        }
         return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     ZDBHomeTastModel * model = _dataArray[indexPath.section];
    switch (model.type) {
        case 1:
        {
            ZDBAlwaysTaskVC * taskVC = [[ZDBAlwaysTaskVC alloc] init];
            [self.navigationController pushViewController:taskVC animated:YES];
        }
            break;
        case 2://图文分享任务
        {
            TaskInfoListModel * oneModel = model.dataArray[indexPath.row];
            ZDBShareCircleViewController * shareCircleVC =  [[ZDBShareCircleViewController alloc] init];
            shareCircleVC.id = oneModel.id;
            [self.navigationController pushViewController:shareCircleVC animated:YES];
            shareCircleVC.taskSuccess = ^{
                [self getTaskData];
            };
        }
            break;
        case 3:
        {
            TaskRegistersModel * twoModel = model.dataArray[indexPath.row];
            ZDBExtensionViewController * extensionVC = [[ZDBExtensionViewController alloc] init];
            extensionVC.id = twoModel.id;
            [self.navigationController pushViewController:extensionVC animated:YES];
            extensionVC.taskSuccess = ^{
                [self getTaskData];
            };
            
        }
            break;
        case 4:
        {
            TaskRechargesModel * threeModel = model.dataArray[indexPath.row];
            ZDBRechargeViewController * extensionVC = [[ZDBRechargeViewController alloc] init];
            extensionVC.id = threeModel.id;
            [self.navigationController pushViewController:extensionVC animated:YES];
            extensionVC.taskSuccess = ^{
                [self getTaskData];
            };
            
        }
            break;
            
        default:
            break;
    }
    
}
@end
